package cfdt.ldl.web.filter;


import cfdt.common.wrapper.RequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 请求过滤器，需要先包装报文，才能进行验签
 *
 * <pre>
 * Modify Information:
 * Author        Date          Description
 * ============ =========== ============================
 * liyuejiang     2021年12月07日       Create this file
 * </pre>
 */
@Component
public class RequestFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger("RequestFilter");

    @Override
    public void init(FilterConfig filterConfig) {
        // Do nothing
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(request instanceof HttpServletRequest){
            HttpServletRequest hsrequest = (HttpServletRequest)request;
            if( StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE) ){
                chain.doFilter(new RequestWrapper(hsrequest),response);
            }else {
                chain.doFilter(request,response);
            }
        }else {
            chain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {
        // Do nothing
    }
}
